//
//  SettingsViewController.m
//  We365
//
//  Created by Bui Thien An on 12/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SettingsViewController.h"
#import "MainViewController.h"
#import "SBJson.h"
#import "LocationViewController.h"

@implementation SettingsViewController
@synthesize table;
@synthesize conn;
@synthesize webData;
@synthesize locationName;
@synthesize locationGotCha;
@synthesize alertGPS;

int measureIndexTemp;
float distanceTemp;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)init
{
    self = [super init];
    [self setLocationName:nil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        NSMutableDictionary *settings = [[NSMutableDictionary alloc] initWithDictionary:[Settings getAllSettings]];
        if(measureIndexTemp == 0)
            [settings setValue:kKmC forKey:kMeasureKind];
        else
            [settings setValue:kMilesF forKey:kMeasureKind];
        [settings setValue:[NSNumber numberWithFloat:distanceTemp] forKey:kDistance];
        [Settings setAllSettings:settings];
        [Settings saveSettings];
        [settings release];
        
        NSLog(@"goBack function");
        [UIView beginAnimations:@"animation" context:nil];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
        [self.navigationController popViewControllerAnimated:NO];
        [UIView commitAnimations];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getLocationName];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getLocationName];
    
    table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:BGTable]];
    table.separatorColor = [UIColor yellowColor];
    
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [self setConn:nil];
    [self setWebData:nil];
    [self setLocationName:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSString *)title
{
    return @"Settings";
}

- (void)getLocationName
{
    CLLocation *location = [MainViewController getLocation];
    
    if(location == nil)
        return;
    
    NSString *urlString = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=true", location.coordinate.latitude, location.coordinate.longitude];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    conn = [NSURLConnection connectionWithRequest:request delegate:self]; 
}

//NSURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(!webData)
        webData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [webData release];
    webData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseString = [[[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding] autorelease];
    NSDictionary *root = [responseString JSONValue];
    
    NSArray *results = [root objectForKey:@"results"];
    NSDictionary *result = [results objectAtIndex:0];
    locationName = [(NSString *)[result objectForKey:@"formatted_address"] retain];
    
    [table reloadData];
    
    webData = nil;
    conn = nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
        return 2;
    else 
        return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int section = [indexPath section];
    int row = [indexPath row];
    
    UITableViewCell *cell = nil;
    
    if(section == 0)
    {
        NSDictionary *settings = [Settings getAllSettings];
        if(row == 0)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MeasureCell"] autorelease];
            
            UILabel *name = [[[UILabel alloc] initWithFrame:CGRectMake(7, 7, 100, 30)] autorelease];
            name.text = @"Measure";
            [cell.contentView addSubview:name];
            
            UISegmentedControl *measure = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Km/°C", @"Miles/°F", nil]] autorelease];
            [measure setFrame:CGRectMake(140, 7, 150, 30)];
            if([[settings objectForKey:kMeasureKind] isEqualToString:kKmC])
            {
                measureIndexTemp = 0;
                [measure setSelectedSegmentIndex:0];
            }
            else
            {
                measureIndexTemp = 1;
                [measure setSelectedSegmentIndex:1];
            }
            [measure addTarget:self action:@selector(segmentedValueChange:) forControlEvents:UIControlEventValueChanged];
            [cell.contentView addSubview:measure];
        }
        else
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DistanceCell"] autorelease];
            
            UILabel *name = [[[UILabel alloc] initWithFrame:CGRectMake(7, 7, 100, 30)] autorelease];
            name.text = @"Distance";
            name.tag = 0;
            [cell.contentView addSubview:name];
            
            UISlider *distance = [[[UISlider alloc] initWithFrame:CGRectMake(7, 37, 285, 10)] autorelease];
            [distance setMinimumValue:100];
            [distance setMaximumValue:50000];
            [distance setValue:[[settings objectForKey:kDistance] floatValue]];
            [distance addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
            distance.tag = 1;
            [cell.contentView addSubview:distance];
            
            UILabel *result = [[[UILabel alloc] initWithFrame:CGRectMake(210, 7, 80, 30)] autorelease];
            result.text = [NSString stringWithFormat:@"%.0f m", distance.value];
            result.tag = 2;
            result.textColor = [UIColor redColor];
            result.textAlignment = UITextAlignmentRight;     
            distanceTemp = distance.value;
            [cell.contentView addSubview:result]; 
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }
    else
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyLocationCell"] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        UILabel *address = [[[UILabel alloc] initWithFrame:CGRectMake(7, 0, 270, 60)] autorelease];
        address.textColor = [UIColor blueColor];
        address.textAlignment = UITextAlignmentCenter;
        address.backgroundColor = [UIColor clearColor];
        address.font = [UIFont boldSystemFontOfSize:14];
        if(locationName == nil)
            address.text = @"";
        else
            address.text = locationName;
        address.lineBreakMode = UILineBreakModeWordWrap;
        address.numberOfLines = 0;
        [cell.contentView addSubview:address];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int section = [indexPath section];
    int row = [indexPath row];
    
    if(section == 1 && row == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Update location" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Automatic", @"Manual", nil];
        [alert show];
        [alert release];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0)
        return @"Measure and Distance";
    else 
        return @"My location";
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *titleHeader = [self tableView:tableView titleForHeaderInSection:section];
    if (titleHeader == nil) {
        return nil;
    }
    
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(0, 20, tableView.bounds.size.width, 30);
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor redColor];
    label.font = [UIFont boldSystemFontOfSize:20.0f];
    label.shadowColor = [UIColor blackColor];
    label.shadowOffset = CGSizeMake(1, 0.8f);
    label.textAlignment = UITextAlignmentCenter;
    label.text = titleHeader;
    
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)]autorelease];
    //view.frame = CGRectMake(0, 0, tableView.bounds.size.width, 50);
    
    [view addSubview:label];
    //[label autorelease];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return 50;  
    }
    else
        return 0;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath section] == 0 && [indexPath row] == 1)
        return 60;
    else
        return 60;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //automatic
    if(buttonIndex == 1)
    {
        alertGPS = [[UIAlertView alloc] initWithTitle:@"Getting Location..." message:@" " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
        UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
        progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        [alertGPS addSubview:progress];
        [progress startAnimating];
        [progress release];
        
        [alertGPS show];
        
        if(locationGotCha == nil)
            locationGotCha = [[LocationGotcha alloc] init];
        locationGotCha.delegate = self;
        [locationGotCha startUpdates];
    }
    //manual
    else if(buttonIndex == 2)
    {
        LocationViewController *locationViewController = [[LocationViewController alloc] init];
        [self.navigationController pushViewController:locationViewController animated:YES];
        [locationViewController release];
    }
}

- (IBAction)sliderValueChange:(id)sender
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:0];
    UITableViewCell *distanceCell = [table cellForRowAtIndexPath:path];
    UILabel *result = (UILabel *)[distanceCell.contentView viewWithTag:2];
    UISlider *distance = (UISlider *)sender;
    result.text = [NSString stringWithFormat:@"%.0f m", distance.value];           
    distanceTemp = distance.value;
}

- (IBAction)segmentedValueChange:(id)sender
{
    UISegmentedControl *measure = (UISegmentedControl *)sender;
    measureIndexTemp = measure.selectedSegmentIndex;
}

- (void)newPhysicalLocation:(CLLocation *)location
{
    [MainViewController setLocation:[location retain]];
    [alertGPS dismissWithClickedButtonIndex:0 animated:YES];
    [self getLocationName];
}

- (void)dealloc {
    [table release];
    [conn release];
    [webData release];
    //[locationName release];
    [locationGotCha release];
    [alertGPS release];
    [super dealloc];
}

@end
